package cn.whx.hrm.exception;

import cn.whx.hrm.util.AjaxResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@RestControllerAdvice
public class HrmExceptionHandler {
    //算术异常
    @ExceptionHandler(ArithmeticException.class)
    public AjaxResult arithmeticException(ArithmeticException e){
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }
    //所有异常
    @ExceptionHandler(Exception.class)
    public AjaxResult exception(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }
    //jsr303异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException e){
        List<FieldError> errors = e.getBindingResult().getFieldErrors();
        HashMap<Object, Object> map = new HashMap<>();
        errors.stream().forEach(field -> {
            map.put(field.getField(), field.getDefaultMessage());
        });
        return AjaxResult.me().setSuccess(false).setMessage(map.toString());
    }
}
